import requests
import time
import pymysql

ID = "ww7b4086d88a144eec"
SECRET = "Yy-hdts7KZHFDO8tzwWTNUfPiGyssUOo8XAPz2IOnbA"
url_get_access_token = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + ID + "&corpsecret=" + SECRET

#获取access_token#
def get_access_token(ID,SECRET):
    access_token_json = requests.get(url_get_access_token).json()
    while access_token_json['errcode'] != 0:
        print(access_token_json['errcode'])
        get_access_token(ID, SECRET)
        time.sleep(2)
    access_token = access_token_json['access_token']
    return access_token

#获取通讯录部门列表#
url_get_department_list = "https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token=" + get_access_token(ID,SECRET) + "&id=1"

db = pymysql.connect(host="localhost", user="root", password="zcxvbmn", database="weixindb")
cursor = db.cursor()

def get_department_list():
    department_list = requests.get(url_get_department_list).json()['department']
    print(department_list)
    clean_department_list_sql = "delete from department_list"
    cursor.execute(clean_department_list_sql)
    db.commit() #清空数据库
    for department in department_list:
        id = department['id']
        name = repr(department['name'])
        parentid = department['parentid']
        department_order = department['order']
        #cols = ", ".join('{}'.format(k) for k in department.keys())#order为sql保留字
        #val_cols = ', '.join('{}'.format(k) for k in department.values())
        sql = "insert into department_list values(%s,%s,%s,%s)" % (id, name, parentid, department_order)
        #res_sql = sql % (val_cols)
        try:
            cursor.execute(sql)
            db.commit()
        except:
            print(sql)
    return

get_department_list()